package org.luxor.generator.service;

import org.luxor.generator.config.GeneratorPropertie;
import org.luxor.generator.constant.GeneratorConstants;
import org.luxor.generator.entity.ProjectModel;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 项目模版参数配置
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service
public class SysProjectModelService {

    @Resource
    private GeneratorPropertie propertie;
    @Resource
    private HttpSession session;

    /**
     * 获取字段类型映射关系
     *
     * @return
     */
    public Map<String, String> getTypeMappings() {
        return propertie.getTypeMappings();
    }

    /**
     * 获取,当前项目模版参数
     *
     * @return
     */
    public ProjectModel info() {
        Object sessionAttr = session.getAttribute(GeneratorConstants.PROJECT_MODEL_KEY);
        if (sessionAttr != null && sessionAttr instanceof ProjectModel) {
            return (ProjectModel) sessionAttr;
        }
        ProjectModel projectModel = propertie.getProjectModel();
        return projectModel;
    }

    /**
     * 保存,当前项目模版参数
     *
     * @param projectModel
     * @return
     */
    public ProjectModel save(ProjectModel projectModel) {
        ProjectModel sessionVal = new ProjectModel();
        BeanUtils.copyProperties(propertie.getProjectModel(), sessionVal);
        BeanUtils.copyProperties(projectModel, sessionVal);

        session.setAttribute(GeneratorConstants.PROJECT_MODEL_KEY, sessionVal);
        return projectModel;
    }

    /**
     * 重置,当前数据源配置
     * @return
     */
    public ProjectModel reset() {
        session.removeAttribute(GeneratorConstants.PROJECT_MODEL_KEY);
        return propertie.getProjectModel();
    }

}
